package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/boyane/chartroom/common/message"
	"github.com/boyane/chartroom/server/utils"
	"net"
)

// 处理短消息控制器
type Sms struct {

}

func (this *Sms) HandleSmsGroupMes(mes *message.Message) (err error) {
	var groupMes message.SmsGroupEmitMes
	if err = json.Unmarshal([]byte(mes.Data), &groupMes);err != nil{
		fmt.Println("HandleSmsGroupMes -> json.Unmarshal fail err =", err)
		return
	}

	// 循环发送消息
	for key, val := range OnlineUsers.onlineUsers{
		if key == groupMes.UserId{
			continue
		}
		this.emitGroupMes(val.Conn, groupMes)
	}

	return
}

func (this *Sms) emitGroupMes(conn net.Conn, mesRes message.SmsGroupEmitMes){
	var mes message.Message
	mes.Type = message.SmsGroupEmitResMesType

	bytes, err := json.Marshal(mesRes)
	if err != nil{
		fmt.Println("emitGroupMes -> fail err=", err)
		return
	}

	mes.Data = string(bytes)

	bytes, err = json.Marshal(mes)
	if err != nil{
		fmt.Println("emitGroupMes -> fail err=", err)
		return
	}

	ts := utils.Transfer{}
	ts.Conn = conn

	if err = ts.WritePkg(bytes);err != nil{
		fmt.Println("emitGroupMes -> ts.WritePkg err=", err)
	}
}